package com.app.island.cash.requestrisk.newwork

import android.content.Context
import com.app.island.cash.requestrisk.bean.CallbackBean
import com.app.island.cash.requestrisk.util.Base64Util
import com.app.island.cash.requestrisk.util.HmacMd5Utils
import com.google.gson.Gson

/**
 * @CreateDate: 2020/9/8 15:44
 * @Description:
 * @Author: kayLau
 */
class HttpSendReq private constructor() {
    var appId: String = ""
    var appSecret: String? = null
    var uploadUrl: String? = null
    var phoneNum: String = ""
    var context: Context? = null
    var transactionId: String = ""
    var borrowId: String = ""
    fun onPostReq(reqUrl: String, reqJsonStr: String, signMsg: String) {
        DataAsyncTask(reqUrl, reqJsonStr, signMsg).execute()
    }

    fun uploadSdkLog(
        syncType: String?,
        syncState: Boolean,
        syncCode: Int,
        syncMsg: String?,
        uploadCount: Int
    ) {
        val customEventBean: CallbackBean = CallbackBean()
        if (context != null) {
            customEventBean.packageName = context!!.getPackageName()
        }
        customEventBean.appId = appId
        customEventBean.sdkVer = "1.0.0"
        customEventBean.syncCode = syncCode
        customEventBean.syncMsg = syncMsg
        customEventBean.isSyncState = syncState
        customEventBean.borrowId = borrowId
        customEventBean.transactionId = transactionId
        customEventBean.userPhone = phoneNum
        customEventBean.uploadCount = uploadCount
        customEventBean.syncType = syncType
        var toJson: String = Gson().toJson(customEventBean).trim({ it <= ' ' })
        LogUtil.e("uploadSyncStatus: " + toJson)
        toJson = Base64Util.encode(toJson.toByteArray())
        var sign: String
        try {
            sign = HmacMd5Utils.EncryptHMacMd5(toJson.toByteArray(charset("UTF-8")), appSecret)
        } catch (e: Exception) {
            sign = ""
            collectException("uploadSyncSdkLog: " + e.toString())
        }
        val url: String = uploadUrl + "/api/v1/log/post"
        val bufferReq: StringBuffer = StringBuffer()
        bufferReq.append("sdklog").append("=").append(toJson)
        instance!!.onPostReq(url, bufferReq.toString(), sign)
    }

    fun collectException(errorMsg: String?) {
        uploadSdkLog(DataManager.Companion.TYPE_COMMON, false, -2, errorMsg, 0)
    }

    fun collectException(syncType: String?, errorMsg: String?) {
        uploadSdkLog(syncType, false, -2, errorMsg, 0)
    }

    companion object {
        @JvmStatic
        @get:Synchronized
        var instance: HttpSendReq? = null
            get() {
                if (field == null) {
                    field = HttpSendReq()
                }
                return field
            }
            private set
    }
}